`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    02:42:26 05/02/2013 
// Design Name: 
// Module Name:    reg_set 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module reg_set(
	 input clk_50Mhz,
	 input reset_b,
    input [7:0] result,
    output reg [3:0] regA,
    output reg [3:0] regB,
    input read,
    input [1:0] addr_i,
    input [3:0] data_i,
    output reg [15:0] data_o,
    input LDR,
	 input result_pulse
    );
	 
	 reg [3:0] A, B, C, D;
	 reg [3:0] tmp_result;
	 
	 
	 //assign tmp_result = result;
	 
	 	//Load conditions
	 always @(posedge clk_50Mhz, negedge reset_b) begin
		if ((addr_i == 2'b00) && (LDR == 1))  
		begin
			A = data_i;
		end
		else if ((addr_i == 2'b01) && (LDR == 1))
		begin
			B = data_i;
		end
		else if ((addr_i == 2'b10) && (LDR == 1))
		begin
			C = data_i;
		end
		else if ((addr_i == 2'b11) && (LDR == 1))
		begin
			D = data_i;
		end
	end
	
	
	//Sum, Mult, Cmp Conditions
	always @(posedge clk_50Mhz, negedge reset_b) begin
		if (data_i[3:2] == 2'b00)
		begin
			regA = A;
		end 
		else if (data_i[3:2] == 2'b01)
		begin
			regA = B;
		end
		else if (data_i[3:2] == 2'b10)
		begin
			regA = C;
		end
		else if (data_i[3:2] == 2'b11)
		begin
			regA = D;
		end
		
		
		if (data_i[1:0] == 2'b00)
		begin
			regB = A;
		end 
		else if (data_i[1:0] == 2'b01)
		begin
			regB = B;
		end
		else if (data_i[1:0] == 2'b10)
		begin
			regB = C;
		end
		else if (data_i[1:0] == 2'b11)
		begin
			regB = D;
		end
	end
		
	//Concatenate Result
	always @(posedge clk_50Mhz, negedge reset_b) begin
		if ((result[3:0] <= 15) && result [7:4] == 4'b0000)
		begin
			tmp_result = result [3:0];
		end
		else if (result [7:4] >= 4'b0001)
		begin
			tmp_result = result [7:4];
		end
	end
	
	//result stored into regs
	always @(posedge clk_50Mhz, negedge reset_b) begin
		if((addr_i == 2'b00) && (result_pulse == 1))
		begin
			A <= tmp_result;
		end
		else if((addr_i == 2'b01) && (result_pulse == 1))
		begin
			B <= tmp_result;
		end
		else if((addr_i == 2'b10) && (result_pulse == 1)) 
		begin
			C <= tmp_result;
		end
		else if((addr_i == 2'b11) && (result_pulse == 1))
		begin
			D <= tmp_result;
		end
	end


	// data out
	always @(posedge clk_50Mhz, negedge reset_b) begin
		if(read == 1) 
		begin
			data_o <= {A,B,C,D};
		end
		/*else if(addr_i == 2'b01 && read == 1) 
		begin
			data_o <= B;
		end
		else if(addr_i == 2'b10 && read == 1) 
		begin
			data_o <= C;
		end
		else if(addr_i == 2'b11 && read == 1) 
		begin
			data_o <= D;
		end */
	end
endmodule

